package br.com.beautycenter.view;

import br.com.beautycenter.DAO.PersisteDespesas;
import br.com.beautycenter.DAO.PersisteTipoDespesa;
import br.com.beautycenter.Funcionalidades.Swing;
import br.com.beautycenter.Funcionalidades.Validacoes;
import br.com.beautycenter.bean.Despesas;
import br.com.beautycenter.bean.TipoDespesa;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;

public class CadastroDespesas extends javax.swing.JFrame {

    PersisteDespesas persisteDespesas = new PersisteDespesas();
    PersisteTipoDespesa persisteTipoDespesa = new PersisteTipoDespesa();
    
    Despesas despesa = new Despesas();
    TipoDespesa tipoDespesa = new TipoDespesa();
    
    static List<Despesas> listaDespesas = new ArrayList<Despesas>();
    /**
     * operacao = 0 -> salvar operacao = 1 -> atualizar operacao = 2 -> excluir
     */
    int operacao = 0;
    int posicao = -1;

    private void ativarBotoesIniciar() {
        listaDespesas = persisteDespesas.retornarDespesas();
        if (listaDespesas.isEmpty()) {
            btnNovo.setEnabled(false);
            txtValor.requestFocus();
        } else {
            btnSalvar.setEnabled(false);
            btnCancelar.setEnabled(false);
            limparCampos();
            desativarCampos();
        }
    }

    public void iniciarTela() {
        ativarBotoesIniciar();
        preencherComboTipoDespesa();
    }

    public void limparCampos() {
        Swing.zerarCampos(jPDespesas.getComponents());
        txtDescricao.setText(null);
    }

    public void ativarCampos() {
        Swing.ativarCampos(jPDespesas.getComponents());
        txtDescricao.setEnabled(true);
    }

    public void desativarCampos() {
        Swing.desativarCampos(jPDespesas.getComponents());
        txtDescricao.setEnabled(false);
    }

    private void ativarBotoesSalvarCancelarSair() {
        Swing.desativarCampos(jPanelBotoes.getComponents());
        btnSalvar.setEnabled(true);
        btnCancelar.setEnabled(true);
        btnSair.setEnabled(true);
    }

    public boolean validarDescricao() {
        if (txtDescricao.getText().trim().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Informe uma descrição para despesa.");
            txtDescricao.requestFocus();
            return false;
        }

        despesa.setDescricao(txtDescricao.getText().trim());
        return true;
    }

    public boolean validarValor() {
        Double valor = Validacoes.validarCampoMoeda(txtValor.getText().trim());

        if (valor != null) {
            despesa.setValor(valor);
            return true;
        } else {
            JOptionPane.showMessageDialog(null, "Valor informado é invalido!");
            txtValor.requestFocus();
            return false;
        }
    }

    public void novo() {
        operacao = 0;
        limparCampos();
        ativarCampos();

        ativarBotoesSalvarCancelarSair();
        txtValor.requestFocus();
    }

    public void salvar() {
        if (preencherDespesa()) {
            iniciarTela();
        }
    }

    public void cancelar() {
        if (!listaDespesas.isEmpty()) {
            limparCampos();
            desativarCampos();
            btnNovo.setEnabled(true);
            btnSalvar.setEnabled(false);
            btnCancelar.setEnabled(false);
        } else {
            limparCampos();
        }
    }

    public void sair() {
        dispose();
    }

    public boolean preencherDespesa() {
        despesa = new Despesas();

        if (validarValor() && validarDescricao()) {
            
                //Pega a data do sistema operacional
            Date date = new Date();  
            despesa.setDataCadastro(date);
            
                //Seleciona o tipo de despesa
             int selecionado = jComboTipoDespesa.getSelectedIndex();
        
        //se não for o primeiro, então é válido
        if(selecionado > 0){
            tipoDespesa = new TipoDespesa();
            tipoDespesa.setTipoDespesa(jComboTipoDespesa.getSelectedItem().toString());
            tipoDespesa = persisteTipoDespesa.retornarTipoDespesaPeloNome(tipoDespesa).get(0);
            despesa.setDespesa(tipoDespesa);
        }
            
            persisteDespesas.salvar(despesa);
            
            JOptionPane.showMessageDialog(null, "DESPESA SALVA COM SUCESSO.");
            limparCampos();
            desativarCampos();
            ativarBotoesIniciar();
            btnNovo.setEnabled(true);

            return true;
        } else {
            return false;
        }
    }

    public void preencherComboTipoDespesa(){
        jComboTipoDespesa.removeAllItems();
        jComboTipoDespesa.addItem("Selecione um tipo de despesa.");
        for(TipoDespesa item: persisteTipoDespesa.retornarTipoDespesa()){
            jComboTipoDespesa.addItem(item.getTipoDespesa());
        }
    }
    
    public CadastroDespesas() {
        initComponents();
        iniciarTela();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanelBotoes = new javax.swing.JPanel();
        btnNovo = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        jPDespesas = new javax.swing.JPanel();
        jLabelDescricao = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescricao = new javax.swing.JTextArea();
        jLabelValor = new javax.swing.JLabel();
        txtValor = new javax.swing.JTextField();
        jLabelTipo = new javax.swing.JLabel();
        jComboTipoDespesa = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ERP BEUTY CENTER - Cadastro de Despesas");
        setBackground(new java.awt.Color(255, 255, 255));

        jPanelBotoes.setPreferredSize(new java.awt.Dimension(500, 45));

        btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/beautycenter/img/Novo.png"))); // NOI18N
        btnNovo.setToolTipText("NOVO");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/beautycenter/img/Salvar.png"))); // NOI18N
        btnSalvar.setToolTipText("SALVAR");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/beautycenter/img/Cancelar.png"))); // NOI18N
        btnCancelar.setToolTipText("LIMPAR");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/beautycenter/img/Sair.png"))); // NOI18N
        btnSair.setToolTipText("SAIR");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanelBotoesLayout = new javax.swing.GroupLayout(jPanelBotoes);
        jPanelBotoes.setLayout(jPanelBotoesLayout);
        jPanelBotoesLayout.setHorizontalGroup(
            jPanelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelBotoesLayout.createSequentialGroup()
                .addContainerGap(114, Short.MAX_VALUE)
                .addComponent(btnNovo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSalvar)
                .addGap(5, 5, 5)
                .addComponent(btnCancelar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSair)
                .addGap(109, 109, 109))
        );
        jPanelBotoesLayout.setVerticalGroup(
            jPanelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelBotoesLayout.createSequentialGroup()
                .addGroup(jPanelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(btnSalvar)
                        .addComponent(btnCancelar)
                        .addComponent(btnSair, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addComponent(btnNovo))
                .addGap(0, 4, Short.MAX_VALUE))
        );

        jPDespesas.setBackground(new java.awt.Color(255, 255, 255));

        jLabelDescricao.setText("Descrição:");

        txtDescricao.setColumns(20);
        txtDescricao.setRows(5);
        jScrollPane1.setViewportView(txtDescricao);

        jLabelValor.setText("Valor:");

        jLabelTipo.setText("Tipo:");

        jComboTipoDespesa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "" }));

        javax.swing.GroupLayout jPDespesasLayout = new javax.swing.GroupLayout(jPDespesas);
        jPDespesas.setLayout(jPDespesasLayout);
        jPDespesasLayout.setHorizontalGroup(
            jPDespesasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPDespesasLayout.createSequentialGroup()
                .addGroup(jPDespesasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPDespesasLayout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addGroup(jPDespesasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabelTipo)
                            .addComponent(jLabelValor))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPDespesasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jComboTipoDespesa, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(jPDespesasLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabelDescricao)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPDespesasLayout.setVerticalGroup(
            jPDespesasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPDespesasLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPDespesasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelValor)
                    .addComponent(txtValor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPDespesasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabelTipo)
                    .addComponent(jComboTipoDespesa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPDespesasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelDescricao)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(32, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(jPDespesas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPDespesas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        novo();
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        salvar();
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        cancelar();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        sair();
    }//GEN-LAST:event_btnSairActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnSair;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JComboBox jComboTipoDespesa;
    private javax.swing.JLabel jLabelDescricao;
    private javax.swing.JLabel jLabelTipo;
    private javax.swing.JLabel jLabelValor;
    private javax.swing.JPanel jPDespesas;
    private javax.swing.JPanel jPanelBotoes;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea txtDescricao;
    private javax.swing.JTextField txtValor;
    // End of variables declaration//GEN-END:variables
}